package com.naiterui.ehp.bs.esign.service.impl;

import com.google.common.collect.Lists;
import com.naiterui.ehp.bp.bo.groupConsult.GroupConsultPreSignBO;
import com.naiterui.ehp.bp.bo.groupConsult.GroupConsultPreSignParamBO;
import com.naiterui.ehp.bp.bo.groupConsult.GroupConsultSignParamBO;
import com.naiterui.ehp.bp.bo.patient.PatientInquirerBO;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.esign.api.ISignService;
import com.naiterui.ehp.bs.esign.api.bjca.vo.SignFileUploadVO;
import com.naiterui.ehp.bs.esign.api.vo.SignAccountVO;
import com.naiterui.ehp.bs.esign.api.vo.SignFileSnVO;
import com.naiterui.ehp.bs.esign.exception.ExceptionCodes;
import com.naiterui.ehp.bs.esign.feign.IPatientFeignClient;
import com.naiterui.ehp.bs.esign.repository.mysql.IEsignRecomEsignDoctorRepository;
import com.naiterui.ehp.bs.esign.service.IDoctorService;
import com.naiterui.ehp.bs.esign.service.IEsignService;
import com.naiterui.ehp.bs.esign.service.IGroupConsultService;
import com.naiterui.ehp.bs.esign.utils.GroupConsultPdfUtil;
import com.naiterui.ehp.bs.esign.vo.esign.PreSignResultVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author gaoliangliang
 * @date 2022/8/3
 * @since 0.0.1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupConsultServiceImpl implements IGroupConsultService {

    private static final String HOSPITAL_NAME = ConfigUtil.getString("ehp.hospital.name");
    @Value("${file.base.prefix}")
    private String basePath;

    private final IEsignRecomEsignDoctorRepository recomEsignDoctorRepository;
    private final GroupConsultPdfUtil groupConsultPdfUtil;
    private final IPatientFeignClient patientFeignClient;
    private final IDoctorService doctorService;
    private final IEsignService esignService;
    private final ISignService signService;

    @Override
    public GroupConsultPreSignBO preSign(GroupConsultPreSignParamBO preSignParamBO) throws BusinessException {

        log.info("会诊签名生成pdf文件开始, preSignParamBO={}", preSignParamBO);
        String filePath = "";
        //获取就诊人信息
        List<PatientInquirerBO> inquirerBOS = patientFeignClient.getPatientInquirer(Lists.newArrayList(preSignParamBO.getInquirerId()));
        if (CollectionUtils.isEmpty(inquirerBOS)) {
            log.error("就诊人信息不存在：inquirerId={}", preSignParamBO.getInquirerId());
            throw new BusinessException(ExceptionCodes.USER_NOT_EXIST);
        }
        PatientInquirerBO inquirer = inquirerBOS.get(0);
        preSignParamBO.setGender(inquirer.getGender());
        preSignParamBO.setName(inquirer.getName());
        preSignParamBO.setAge(inquirer.getAge());

        try {
            filePath = groupConsultPdfUtil.generatePDF(preSignParamBO);
        } catch (
                Exception e) {
            log.error("会诊PDF生成失败", e);
            throw new BusinessException(ExceptionCodes.GROUP_CONSULT_PDF_CREATE_FAIL);
        }
        log.info("生成pdf文件成功：filepath={}", filePath);

        SignFileUploadVO vo = this.generateFileUploadVO(preSignParamBO);
        vo.setPdfPath(basePath + filePath);

        SignAccountVO signAccountVO = doctorService.getSignAccount(preSignParamBO.fetchDoctorId(), vo.getUnionId());
        //获取预签署id
        signAccountVO.setRequestFrom(SignAccountVO.REQUEST_FROM_PC);
        PreSignResultVO resultVO = esignService.preSignPdf(vo, signAccountVO);
        log.info("会诊资料预签名成功：unionId={}", resultVO.getUniqueId());

        return GroupConsultPreSignBO.builder()
                .filePath(filePath)
                .createdAt(new Date())
                .faceUrl(resultVO.getUrl())
                .uniqueId(resultVO.getUniqueId())
                .build();
    }

    @Override
    public void sign(GroupConsultSignParamBO groupConsultSignBO) throws BusinessException {
        log.info("会诊签名开始,groupConsultSignBO={}", groupConsultSignBO);

        //获取就诊人信息
        List<PatientInquirerBO> inquirerBOS = patientFeignClient.getPatientInquirer(Lists.newArrayList(groupConsultSignBO.getInquirerId()));
        if (CollectionUtils.isEmpty(inquirerBOS)) {
            log.error("就诊人信息不存在：inquirerId={}", groupConsultSignBO.getInquirerId());
            throw new BusinessException(ExceptionCodes.USER_NOT_EXIST);
        }
        PatientInquirerBO inquirer = inquirerBOS.get(0);
        groupConsultSignBO.setGender(inquirer.getGender());
        groupConsultSignBO.setName(inquirer.getName());
        groupConsultSignBO.setAge(inquirer.getAge());

        SignFileUploadVO vo = this.generateFileUploadVO(groupConsultSignBO);
        vo.setPdfPath(basePath + groupConsultSignBO.getPdfPath());
        vo.setUnionId(groupConsultSignBO.getUnionId());
        vo.setAddSignTime(false);

        SignAccountVO signAccountVO = doctorService.getSignAccount(groupConsultSignBO.fetchDoctorId(), groupConsultSignBO.getUnionId());
        signAccountVO.setPin(groupConsultSignBO.getPin());
        signAccountVO.setRequestFrom(SignAccountVO.REQUEST_FROM_PC);
        esignService.sign(vo, signAccountVO);

    }

    private SignFileUploadVO generateFileUploadVO(GroupConsultPreSignParamBO groupConsultPreSignParamBO) {

        Long doctorId = groupConsultPreSignParamBO.fetchDoctorId();
        ISignService.SealPosVO sealPosVO;
        String userType;
        if (GroupConsultSignParamBO.OPTION_TYPE_TARGET == groupConsultPreSignParamBO.getOpinionType()) {
            sealPosVO = this.signService.getSealPosConfig().getGcPosTarget();
            userType = SignFileSnVO.USER_TYPE_OTHER;
        } else {
            sealPosVO = this.signService.getSealPosConfig().getGcPosSource();
            userType = SignFileSnVO.USER_TYPE_DR;
        }
        //拼装vo,文件路径各自配置
        return SignFileUploadVO.builder()
                .bizSn(groupConsultPreSignParamBO.getGroupConsultId() + "")
                .createdAt(groupConsultPreSignParamBO.getSourceOpinionAt())
                .patientAge(groupConsultPreSignParamBO.getAge() + "")
                .patientGender(groupConsultPreSignParamBO.getGender())
                .patientName(groupConsultPreSignParamBO.getName())
                .signFileType(SignFileSnVO.FILE_TYPE_GROUPCONSULT)
                .signUserId(doctorId)
                .signUserType(userType)
                .stampX(sealPosVO.getX())
                .stampY(sealPosVO.getY())
                .keyword(sealPosVO.getKeyword())
                .build();
    }

    private SignFileUploadVO generateFileUploadVO(GroupConsultSignParamBO groupConsultSignParamBO) {

        Long doctorId = groupConsultSignParamBO.fetchDoctorId();
        ISignService.SealPosVO sealPosVO;
        String userType;
        if (GroupConsultSignParamBO.OPTION_TYPE_TARGET == groupConsultSignParamBO.getOpinionType()) {
            sealPosVO = this.signService.getSealPosConfig().getGcPosTarget();
            userType = SignFileSnVO.USER_TYPE_OTHER;
        } else {
            sealPosVO = this.signService.getSealPosConfig().getGcPosSource();
            userType = SignFileSnVO.USER_TYPE_DR;
        }
        //拼装vo,文件路径各自配置
        return SignFileUploadVO.builder()
                .bizSn(groupConsultSignParamBO.getGroupConsultId() + "")
                .createdAt(new Date())
                .patientAge(groupConsultSignParamBO.getAge() + "")
                .patientGender(groupConsultSignParamBO.getGender())
                .patientName(groupConsultSignParamBO.getName())
                .signFileType(SignFileSnVO.FILE_TYPE_GROUPCONSULT)
                .signUserId(doctorId)
                .signUserType(userType)
                .stampX(sealPosVO.getX())
                .stampY(sealPosVO.getY())
                .keyword(sealPosVO.getKeyword())
                .build();
    }

}
